package cn.wizzer.app.web.modules.controllers.user;

import cn.wizzer.app.sys.modules.models.SysCurrency;
import cn.wizzer.app.sys.modules.models.constant.CurrencyConstant;
import cn.wizzer.app.sys.modules.services.SysCurrencyService;
import cn.wizzer.app.user.modules.models.RedPacket;
import cn.wizzer.app.user.modules.models.User;
import cn.wizzer.app.user.modules.services.RedPacketRecordService;
import cn.wizzer.app.user.modules.services.RedPacketService;
import cn.wizzer.app.user.modules.services.UserService;
import cn.wizzer.app.user.modules.services.account.UserRechargeService;
import cn.wizzer.app.web.commons.filter.ApiTokenFilter;
import cn.wizzer.framework.base.model.enums.BizExceptionEnum;
import cn.wizzer.framework.util.Result;
import cn.wizzer.framework.util.param.ParamVerify;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.util.ByteSource;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@IocBean
@At("/api/red/packet")
public class ApiRedPacketController {

    @Inject
    @Reference
    private RedPacketService redPacketService;

    @Inject
    @Reference
    private RedPacketRecordService redPacketRecordService;

    @Inject
    @Reference
    private UserRechargeService userRechargeService;

    @Inject
    @Reference
    private UserService userService;

    @Inject
    @Reference
    private SysCurrencyService currencyService;

    /**
     * 发送红包
     *
     * @param redPacket
     * @return Object
     */
    @At("/send")
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Object send(@Param("..") RedPacket redPacket, @ParamVerify(required = true, name = "tradePwd") String tradePwd) {
        String appid = Mvcs.getReq().getHeader("appid");
        // 校验下是否体验金红包

        SysCurrency currency = currencyService.fetch(redPacket.getCurrencyId());
        if(CurrencyConstant.EXP.equals(currency.getName())){
            return Result.error(BizExceptionEnum.EXP_MONEY_CANNOT_SEND);
        }
        User user = userService.fetch(appid);
        // 游客账号不能发红包
        if (user.isVisitor()) {
            return Result.error(BizExceptionEnum.VISITOR_CANNOT_SEND);
        }
        // 用户‘有效流水’大于‘提现流水额度’才能发红包
        if (user.getTransRestriction().setScale(0, BigDecimal.ROUND_DOWN).compareTo(user.getEffectQuota().setScale(0, BigDecimal.ROUND_DOWN)) > 0) {
            Result.breakWith(BizExceptionEnum.SEND_RED_PACKET_FAILED);
        }
        // 校验交易密码
        String traderPwd = new Sha256Hash(tradePwd, ByteSource.Util.bytes(user.getSalt()), 1024).toHex();
        if (!traderPwd.equals(user.getTransactionPwd())) {
            return Result.error(BizExceptionEnum.PWD_VERIFICATION_ERROR);
        }
        RedPacket result = redPacketService.send(appid, redPacket.getCurrencyId(), redPacket.getQuantity(), redPacket.getType(), redPacket.getTotal(), redPacket.getWish());
        return Result.success(result);
    }

    /**
     * 打开红包
     *
     * @param redPacketId
     * @return Object
     */
    @At("/open")
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Object open(@ParamVerify(required = true, name = "redPacketId") String redPacketId) {
        String appid = Mvcs.getReq().getHeader("appid");
        User user = userService.fetch(appid);
        Map<String, String> map = new HashMap<>();
        map.put("recharged", "no");
        // 游客账号不能抢红包
        if (user.isVisitor()) {
            return Result.success(map);
        }
        // 如果不是内部账号，查询用户是否有充值过（运营要求内部账号不充值也可以抢红包）
        if (!user.isInside() && !userRechargeService.isRecharge(appid)) {
            return Result.success(map);
        }
        return Result.success(redPacketService.open(appid, redPacketId));
    }

    /**
     * 根据红包ID查询打开记录
     *
     * @param redPacketId
     * @return Object
     */
    @At("/list")
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Object list(@ParamVerify(required = true, name = "redPacketId") String redPacketId) {
        String appid = Mvcs.getReq().getHeader("appid");
        return Result.success(redPacketRecordService.listByAscOpened(redPacketId));
    }

    /**
     * 分页查询自己获取到的红包
     *
     * @return Object
     */
    @At("/pageList")
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Object pageList(@ParamVerify(required = true, name = "pageNumber") int pageNumber,
                           @ParamVerify(required = true, name = "pageSize") int pageSize) {
        String appid = Mvcs.getReq().getHeader("appid");
        return Result.success(redPacketRecordService.pageList(appid, pageNumber, pageSize));
    }


}
